package com.aaa.front.controller;


import com.aaa.common.util.BaseController;
import com.aaa.common.util.ConstUtil;
import com.aaa.common.util.Result;
import com.aaa.common.vo.PagePlugin;
import com.aaa.front.config.SpringRabbitDeadLetterMQConfig;
import com.aaa.front.entity.*;
import com.aaa.front.service.IntegralDetailService;
import com.aaa.front.service.TbOrderService;
import com.aaa.front.service.UserDetailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ fileName:  TbOrderController
 * @ description:
 * @ fileName: 李江波
 * @ createTime: 2023-06-29 10:05:38
 * @ version:1.0.0
 */

@RestController
@RequestMapping("tbOrder")
public class TbOrderController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private TbOrderService tbOrderService;

    /**
     * 余额
     */
    @Resource
    private BalanceController balanceController;
    /**
     * 余额详情
     */
    @Resource
    private UserDetailService userDetailService;
    /**
     * 积分
     */
    @Resource
    private IntegralController integralController;
    /**
     * 积分详情
     */
    @Resource
    private IntegralDetailService integralDetailService;


    /**
     * 死信
     */
    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 权限管理需要的字段
     ** @param
     * @return
     */
    @PostMapping("queryMune")
    public Result queryMune(@RequestBody PagePlugin<TbOrder> pagePlugin) {
        return success(tbOrderService.queryMune(pagePlugin));
    }


    /**
     * 查询订单状态
     * @param userId
     * @param orderStatusCode
     * @return
     */
    @GetMapping("queryByIdCode")
    public Result queryByIdCode(Integer userId, Integer orderStatusCode) {
        return success(tbOrderService.queryByIdCode(userId, orderStatusCode));
    }


    /**
     * 分页查询所有数据
     * 如果需要带参数分页请前往Impl中添加
     *
     * @param page 分页对象
     * @return 所有数据
     */
    @PostMapping("queryPage")
    public Result queryPage(@RequestBody PagePlugin<TbOrder> page) {
        return success(this.tbOrderService.queryPage(page));
    }

    /**
     * 查询所有数据
     */
    @GetMapping("/queryAll")
    public Result queryAll() {
        return success(this.tbOrderService.list());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryById")
    public Result queryById(Integer id) {
        return success(this.tbOrderService.getById(id));
    }

    /**
     * 根据订单号查询数据
     *
     * @param tcount 实体对象
     * @return 修改结果
     */
    @PostMapping("queryByOrder")
    public List<TbOrder> queryByOrder(String tcount) {
        QueryWrapper<TbOrder> sqw = new QueryWrapper<>();
        sqw.eq("tcount", tcount);
        return this.tbOrderService.list(sqw);
    }

    /**
     * 新增数据
     *
     * @param tbOrder 实体对象
     * @return 新增结果
     */
    @PostMapping("add")
    @Transactional // 开启事务
    public Result insert(@RequestBody TbOrder tbOrder) {

        Result result = integralController.queryInteg(tbOrder.getUserId(), tbOrder.getStoreId());
        Integral integral = (Integral) result.getData();

        if (tbOrder.getPayStatusCode() != 0 && tbOrder.getPayStatusCode() != null) {
            if (integral.getCredits() == 0) {
                return success(ConstUtil.integral.UNCONSUMED);
            }
            /**
             * 判断积分是否充足
             */
            if (integral.getCredits() - tbOrder.getPayStatusCode() < 0) {
                return success(ConstUtil.integral.UNDERINTEGRATION);
            }
        }
        Double productPrice = tbOrder.getProductPrice();
        tbOrder.setProductPrice(productPrice);
        // 订单创建时间
        tbOrder.setOrderCreateTime(new Date().toLocaleString());
        // 订单状态
        tbOrder.setOrderStatusCode(ConstUtil.OrderStatus.PENDING_PAYMENT);


        //获取订单号
        String tcount = tbOrder.getTcount();

        rabbitTemplate.convertAndSend(SpringRabbitDeadLetterMQConfig.BUSINESS_EXCHANGE_TOPIC_1,"dead.letter.rk.order",tcount);

        return success(this.tbOrderService.save(tbOrder));
    }

    /**
     * 支付成功修改数据
     *
     * @param tbOrder 实体对象
     * @return 修改结果
     */
    @PostMapping("Payupdate")
    @Transactional // 开启事务
    public Result Payupdate(@RequestBody TbOrder tbOrder) {
        if(tbOrder.getOrderStatusCode()==11){
            // 获取用户余额
            Balance balance = (Balance) balanceController.queryUserAndStore(tbOrder.getUserId(), tbOrder.getStoreId()).getData();
            // 获取积分状态
            Integral integral = (Integral) integralController.queryInteg(tbOrder.getUserId(), tbOrder.getStoreId()).getData();
            integral.setUserId(tbOrder.getUserId());
            integral.setStoreId(tbOrder.getStoreId());
            // 判断金额是否充足
            if (balance.getAmount() - tbOrder.getProductPrice() < 0) {
                return success(ConstUtil.integral.BANDEQUACY);
            }


            tbOrder.setOrderPayTime(new Date().toLocaleString());// 支付时间
            tbOrder.setOrderStatusCode(ConstUtil.OrderStatus.PAID);
            boolean payupdate = this.tbOrderService.updateById(tbOrder);


            // 余额详情
            UserDetail userDetail = new UserDetail();
            userDetail.setDetailId(tbOrder.getTcount());
            userDetail.setUserId(tbOrder.getUserId());
            userDetail.setStoreId(tbOrder.getStoreId());
            String substring = tbOrder.getProductPrice().toString().substring(0, tbOrder.getProductPrice().toString().length() - 2);
            userDetail.setExpenditure(substring);

            userDetail.setExpenditureTime(new Date().toLocaleString());

            // 积分详情
            IntegralDetail integralDetail = new IntegralDetail();
            integralDetail.setUserId(tbOrder.getUserId());
            integralDetail.setStoreId(tbOrder.getStoreId());

            // 积分不为空 ，余额为空
            if (tbOrder.getPayStatusCode() != 0 && 0 == tbOrder.getProductPrice()) {
                System.out.println("1111111111");
                tbOrder.setPayType("3");
                // 积分详情操作
                integralDetail.setExpenditure(tbOrder.getPayStatusCode().toString());
                integralDetail.setExpenditureTime(new Date().toLocaleString());
                // 积分操作
                integral.setCredits(integral.getCredits() - tbOrder.getPayStatusCode());

                integralDetailService.save(integralDetail);
                integralController.update(integral);
                // 积分为空 ，余额不为空
            } else if (tbOrder.getPayStatusCode() == 0 && 0 != tbOrder.getProductPrice()) {
                System.out.println("22222222222222");
                // 积分详情操作
                integralDetail.setAccountMoney(substring);
                integralDetail.setRechargeTime(new Date().toLocaleString());
                // 积分操作
                integral.setCredits(integral.getCredits() + Integer.valueOf(substring));
                // 余额操作
                balance.setAmount(balance.getAmount() - tbOrder.getProductPrice());
                integralDetailService.save(integralDetail);
                integralController.update(integral);
                balanceController.update(balance);
                userDetailService.save(userDetail);
                tbOrder.setPayType("2");
                // 积分不为空 ，余额不为空
            } else if (tbOrder.getPayStatusCode() != 0 && 0 != tbOrder.getProductPrice()) {
                System.out.println("3333333333333");
                // 积分详情支出
                integralDetail.setExpenditure(tbOrder.getPayStatusCode().toString());
                integralDetail.setExpenditureTime(new Date().toLocaleString());
                integralDetailService.save(integralDetail);
                // 积分支出操作
                integral.setCredits(integral.getCredits() - tbOrder.getPayStatusCode());
                integralController.update(integral);

                // 余额操作
                balance.setAmount(balance.getAmount() - tbOrder.getProductPrice());
                balanceController.update(balance);
                userDetailService.save(userDetail);

                // 积分详情添加操作
                integralDetail.setAccountMoney(substring);
                integralDetail.setRechargeTime(new Date().toLocaleString());
                // 积分添加操作
                integral.setCredits(integral.getCredits() + Integer.valueOf(substring));
                integralDetailService.save(integralDetail);
                integralController.update(integral);
                tbOrder.setPayType("1");
            }
            return success(payupdate);
        }else{
            return success(ConstUtil.OrderStatus.Comment_timeout_ended);
        }
    }

    /**
     * 取消订单
     *
     * @param tcount 实体对象
     * @return 修改结果
     */
    @PostMapping("Cancelupdate")
    @Transactional // 开启事务
    public Result Cancelupdate(@RequestParam String tcount) {
        List<TbOrder> tbOrdersList = queryByOrder(tcount);
        TbOrder tbOrder = tbOrdersList.get(0);
        if(tbOrder.getOrderStatusCode()==11){
            // 商品已取消
            tbOrder.setOrderStatusCode(ConstUtil.OrderStatus.Comment_timeout_ended);
            return success(this.tbOrderService.updateById(tbOrder));
        }else{
            return success(200);
        }

    }
    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("deleteById")
    public Result delete(Integer id) {
        return success(this.tbOrderService.removeById(id));
    }
    @PostMapping("queryInstance")
    public Result queryInstance(@RequestBody PagePlugin<TbOrder> page) {
        return success(this.tbOrderService.queryInstance(page));
    }
}

